package com.vitaf.cash.app.utils

import android.content.Intent
import android.net.Uri
import android.provider.ContactsContract
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import com.vitaf.cash.app.common.VitafComAct
import com.vitaf.cash.app.utils.log.VitafLog

/**
 * PickContactUtils
 * @Author wwdeng
 * @CreateTime: 2024/11/28 15:23
 * @Annotation：选择联系人
 */
class VitafPickCntUtils(private val proAct: VitafComAct) {

    // 临时回调接收器
    private var pickContactCallback: ((contactName: String, contactMobile: String) -> Unit)? = null

    // 通讯录启动器
    private val contactLauncherBus = proAct.registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
        if (it == null || it.resultCode != AppCompatActivity.RESULT_OK)
            return@registerForActivityResult
        it.data?.data?.let { uri ->
            pickContactAction(uri) // 从返回的Uri解析出联系人
        }
    }

    /** 从通讯录选取联系人 */
    fun startPickContact(callback: (contactName: String, contactMobile: String) -> Unit) {
        pickContactCallback = callback
        try {
            contactLauncherBus.launch(Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Phone.CONTENT_URI))
        } catch (e: Exception){
            VitafLog.e("Pick Contact error: ${e.message}")
        }
    }

    /**
     * 解析联系人数据
     */
    private fun pickContactAction(contactUri: Uri){
        var displayName = ""
        var phoneNumber = ""
        try {
            val projection = arrayOf(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER)
            proAct.contentResolver.query(contactUri, projection, null, null, null)?.use {
                if (it.moveToFirst()) {
                    val nameIndex = it.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)
                    if (nameIndex != -1){
                        displayName = it.getString(nameIndex)
                    }
                    val phoneIndex = it.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)
                    if (phoneIndex != -1){
                        phoneNumber = it.getString(phoneIndex)
                    }
                }
            }
        } catch (e: Exception){
            displayName = ""
            phoneNumber = ""
        }
        pickContactCallback?.invoke(displayName, phoneNumber)
    }
}